package com.baitiaojun.moments.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.domain.user.RabbitMqDuplicate;
import com.baitiaojun.api.domain.moments.UserMoments;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.SnowFlakeUtil;
import com.baitiaojun.moments.mapper.RabbitMqDuplicateMapper;
import com.baitiaojun.moments.service.DuplicateService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @类名 MqDuplicateServiceImpl
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2022/12/3 21:30
 * @版本 1.0
 */
@Service
public class DuplicateServiceImpl implements DuplicateService {

    @Resource
    private RabbitMqDuplicateMapper rabbitMqDuplicateMapper;

    @Override
    public List<RabbitMqDuplicate> getRabbitMqUserDuplicateListByStatus(String status) {
        return rabbitMqDuplicateMapper.selectRabbitMqDuplicateByStatus(status);
    }

    @Override
    public void batchUpdateMqUserDuplicateByIds(List<Long> ids, String status) throws ConditionException {
        int res = rabbitMqDuplicateMapper.updateBatchStatusById(ids, status, new Date());
        if (res == 0) {
            throw new ConditionException("冗余信息状态更新失败");
        }
    }

    @Override
    public void updateStatusById(RabbitMqDuplicate rabbitMqDuplicate) throws ConditionException {
        int res = rabbitMqDuplicateMapper.updateByPrimaryKeySelective(rabbitMqDuplicate);
        if (res == 0) {
            throw new ConditionException("用户冗余信息添加失败");
        }
    }

    @Override
    public Long insertDuplicate(UserMoments userMoments) throws ConditionException {
        if (ObjectUtils.isEmpty(userMoments)) {
            throw new ConditionException("消息不能为空");
        }
        RabbitMqDuplicate mqDuplicate = RabbitMqDuplicate.builder()
                .id(SnowFlakeUtil.getNextId())
                .contentid(userMoments.getId())
                .createtime(new Date())
                .content(JSONObject.toJSONString(userMoments))
                .status(ConstantUtil.DEFAULT_STATUS).build();
        int res = rabbitMqDuplicateMapper.insertSelective(mqDuplicate);
        if (res == 0) {
            throw new ConditionException("冗余存储失败");
        }
        return mqDuplicate.getId();
    }

    @Override
    public String selectStatusById(long id) {
        return rabbitMqDuplicateMapper.selectStatusById(id);
    }

    @Override
    public void deleteDuplicateByContentId(Long contentId) throws ConditionException {
        int res = rabbitMqDuplicateMapper.deleteByContentId(contentId);
        if (res == 0) {
            throw new ConditionException("删除冗余存储失败");
        }
    }
}
